package com.mars.ticket.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mars.ticket.entity.Ticket;
import com.mars.ticket.entity.User;
import com.mars.ticket.exception.WorkException;
import com.mars.ticket.mapper.TicketMapper;
import com.mars.ticket.mapper.UserMapper;
import com.mars.ticket.request.TicketOrderRequest;
import com.mars.ticket.response.TicketOrderResponse;
import com.mars.ticket.response.base.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mars.ticket.service.ITicketOrderService;
import com.mars.ticket.mapper.TicketOrderMapper;
import com.mars.ticket.entity.TicketOrder;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;


/**
 * TicketOrder 实现层
 *
 * @Author wq
 * @Date 2021-04-22
 **/
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class TicketOrderServiceImpl extends ServiceImpl<TicketOrderMapper, TicketOrder> implements ITicketOrderService {

    @Resource
    private TicketMapper ticketMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public void createOrder(Integer userId, Integer ticketId, String username, String idCard) {
        //减少库存
        Ticket ticket = ticketMapper.selectById(ticketId);
        if (Objects.nonNull(ticket)) {
            ticket.setTicketNumber(ticket.getTicketNumber() - 1);
            ticketMapper.updateById(ticket);
        }
        Integer count = baseMapper.selectCount(new LambdaQueryWrapper<TicketOrder>().
                eq(TicketOrder::getUserId, userId).eq(TicketOrder::getTicketId, ticketId));
        if (count > 3) {
            throw new WorkException("该票你已经购买达到上限,最多只能购买四张哦");
        } else {
            if (ticket.getTicketNumber() > 0) {
                TicketOrder ticketOrder = new TicketOrder();
                ticketOrder.setOrderId(getOrderIdByTime());
                ticketOrder.setCreateTime(new Date());
                ticketOrder.setUpdateTime(new Date());
                ticketOrder.setUserId(userId);
                ticketOrder.setUsername(username);
                ticketOrder.setIdCard(idCard);
                ticketOrder.setTicketId(ticketId);
                save(ticketOrder);
            }
        }

    }

    @Override
    public PageInfo<TicketOrderResponse> list(TicketOrderRequest request) {
        IPage<TicketOrder> page = new Page<>(request.getPageNumber(), request.getPageSize());
        LambdaQueryWrapper<TicketOrder> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(request.getOrderId())) {
            wrapper.eq(TicketOrder::getOrderId, request.getOrderId());
        }
        wrapper.orderByDesc(TicketOrder::getCreateTime);

        IPage<TicketOrder> ticketOrderIPage = baseMapper.selectPage(page, wrapper);
        if (!CollectionUtils.isEmpty(ticketOrderIPage.getRecords())) {
            List<TicketOrder> records = ticketOrderIPage.getRecords();
            List<TicketOrderResponse> list = records.stream().map(ticketOrder -> {
                TicketOrderResponse response = new TicketOrderResponse();
                response.setOrderId(ticketOrder.getOrderId());
                Integer ticketId = ticketOrder.getTicketId();
                Ticket ticket = ticketMapper.selectById(ticketId);
                if (Objects.nonNull(ticket)) {
                    response.setStartingPoint(ticket.getStartingPoint());
                    response.setEndingPoint(ticket.getEndingPoint());
                    response.setTrainNumber(ticket.getTrainNumber());
                }
                response.setIdCard(ticketOrder.getIdCard());
                response.setUserId(ticketOrder.getUserId());
                Integer userId = ticketOrder.getUserId();
                User user = userMapper.selectById(userId);
                if (Objects.nonNull(user)) {
                    response.setUsername(user.getNickname());
                }
                response.setCreateTime(ticketOrder.getCreateTime());
                response.setUpdateTime(ticketOrder.getUpdateTime());
                return response;
            }).collect(Collectors.toList());
            return new PageInfo<>(page.getTotal(), list);
        }
        return null;
    }

    @Override
    public List<TicketOrderResponse> orderList(Integer userId) {
        LambdaQueryWrapper<TicketOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TicketOrder::getUserId, userId);
        wrapper.orderByDesc(TicketOrder::getCreateTime);
        List<TicketOrder> ticketOrders = baseMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(ticketOrders)) {
            List<TicketOrderResponse> list = ticketOrders.stream().map(ticketOrder -> {
                TicketOrderResponse response = new TicketOrderResponse();
                response.setOrderId(ticketOrder.getOrderId());
                Integer ticketId = ticketOrder.getTicketId();
                Ticket ticket = ticketMapper.selectById(ticketId);
                if (Objects.nonNull(ticket)) {
                    response.setStartingPoint(ticket.getStartingPoint());
                    response.setEndingPoint(ticket.getEndingPoint());
                    response.setTrainNumber(ticket.getTrainNumber());
                }
                response.setUserId(ticketOrder.getUserId());
                Integer userId1 = ticketOrder.getUserId();
                User user = userMapper.selectById(userId1);
                if (Objects.nonNull(user)) {
                    response.setUsername(user.getNickname());
                }
                response.setCreateTime(ticketOrder.getCreateTime());
                response.setUpdateTime(ticketOrder.getUpdateTime());
                return response;
            }).collect(Collectors.toList());
            return list;
        }
        return null;
    }

    @Override
    public void delete(String orderId) {
        baseMapper.delete(new LambdaQueryWrapper<TicketOrder>().eq(TicketOrder::getOrderId, orderId));
    }

    /**
     * 获取订单ID
     *
     * @return Long
     */
    public static String getOrderIdByTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        StringBuilder result = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result.append(random.nextInt(10));
        }
        return newDate + result;
    }
}